import React from 'react';
import './index.less';

class ToDoListItem extends React.Component {

  state = {
    styleFlag : false,
    textValue : this.props.itemName,
    changeInd : false,
    orgName : this.props.itemName,
    textLimit : 15,
    doFocusInd : true
  }
  //处理勾选
  handleCheck = (id)=>{
		return (event)=>{
			this.props.updateItem(id,event.target.checked);
		}
	}

  handleBlur = (id) => {
    return (event) => {
      const {textValue,changeInd} = this.state;
      if(!changeInd){
        this.setState({styleFlag:false});
        return;
      }
      if(this.props.checkItemNameSame(textValue)){
        alert('任务名称不能重复！');
        //this.focusInput();????????????
        return;
      }
      this.props.updateName(id,textValue);
      this.setState({styleFlag:false});
    }
  }

  handleNameChange = (event) => {
    let {oldTextValue,orgName,textLimit} = this.state;
    if(oldTextValue !== event.target.value && event.target.value !== orgName){
      this.setState({textValue:event.target.value.substring(0,textLimit),changeInd:true});
    }else{
      this.setState({textValue:event.target.value.substring(0,textLimit),changeInd:false});
    }
  }

  focusInput = () =>{
    if(this.textInput === null){
      return;
    }
    this.setState({doFocusInd:false});
    this.textInput.focus();
  }

  handleUpdateName = (id,itemName) => {
    const {styleFlag,textValue} = this.state;
    if(styleFlag){
      return <input value={textValue} ref={input => this.textInput = input} className='updateName-input' onChange={this.handleNameChange} onBlur={this.handleBlur(id)} type="text" autoFocus/>
    }else{
      return <span onDoubleClick={() => {this.setState({styleFlag:true})}}>{itemName}</span>
    }
  }

  render() {
    const {id,itemName,finalInd,deleteItem} = this.props;
    return (
            <div className='todo-item'>
              <div>
                <input type="checkbox" checked={finalInd} onChange={this.handleCheck(id)}/>
                {this.handleUpdateName(id,itemName)}
                </div>
                <span>
                  <svg className='delete-icon' onClick={()=> deleteItem(id) } aria-hidden="true">
                    <use xlinkHref="#delete"></use>
                  </svg>
                </span>
            </div>
    );
  }
}

export default ToDoListItem;
